package br.mg.bhe.ftpobre.fs.data.xml;

import java.util.ArrayList;
import java.util.List;

import javax.swing.table.TableModel;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import br.mg.bhe.ftpobre.util.XmlUtil;
import javax.swing.ImageIcon;
import javax.swing.table.DefaultTableModel;
import org.w3c.dom.NodeList;

public class TableModelParser implements IDocumentParser<TableModel> {

	private static final String[] columnNames = new String[] {
		"directory", "filename", "Size"
	};
	
	@Override
	public Document parse(TableModel data) {
		Object[][] values = getData(data);
		Document doc;
		try {
			doc = XmlUtil.createEmptyDocument();
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
		
		List<Element> nodes = createDocumentNodes(doc, values);
		Element root = doc.createElement("fileview");
		
		
		for (Element e : nodes) {
			root.appendChild(e);
		}
		
		doc.appendChild(root);
		return doc;
	}

	@Override
	public TableModel parse(Document doc) {
            return new DefaultTableModel(this.getData(doc), columnNames) {

                @Override
                public Class<?> getColumnClass(int columnIndex) {
                    if (columnIndex == 0) {
                        return ImageIcon.class;
                    } else {
                        return super.getColumnClass(columnIndex);
                    }
                }

                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };
	}

	private List<Element> createDocumentNodes(Document doc, Object[][] data) {
		List<Element> nodes = new ArrayList<Element>();
		
		for (Object[] row : data) {
			Element ancestor = doc.createElement("file");
			
			for (byte i = 0; i < row.length; i++) {
				Element child = doc.createElement(columnNames[i]);
				Object column = row[i];
				child.setTextContent((column != null) ? column.toString() : "");
				ancestor.appendChild(child);
			}
			nodes.add(ancestor);
		}
		
		return nodes;
	}
	
	private Object[][] getData(TableModel model) {
		Object[][] data = new Object[model.getRowCount()][model.getColumnCount()];
		
		for (int i = 0; i < model.getRowCount(); i++) {
			for (byte j = 0; j < model.getColumnCount(); j++) {
				data[i][j] = model.getValueAt(i, j);
			}
		}
		
		return data;
	}

        private Object[][] getData(Document doc) {
            NodeList nodes = doc.getFirstChild().getChildNodes();
            for (int i = 0; i < nodes.getLength(); i++) {
                System.out.println(nodes.item(i).getTextContent());
            }

            return null;
        }
}